﻿using PokemonTools.Entity;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace PokemonClientToos.Entity
{
    public class Robot
    {
        private Robot() { }
        public static readonly Robot instance = new Robot();

        Stopwatch stopwatch = new Stopwatch();
        public static Socket clientSocket = null;
        public static Thread thread = null;
        private string _nickName { get; set; }

        #region Http请求
        public void HttpGet(string Url, string postDataStr)
        {
            try
            {
                string uri = Url + "?" + postDataStr;
                HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
                request.Method = "GET";
                request.ProtocolVersion = new Version(1, 1);

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using (Stream stream = response.GetResponseStream())
                {
                    int totalLength = (int)response.ContentLength;
                    int numBytesRead = 0;
                    while (numBytesRead < totalLength)
                    {
                        int num = stream.Read(GameRole.dataBytes, numBytesRead, 1024);
                        numBytesRead += num;
                        if (num == 0)
                            break;
                    }
                }

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region Tcp请求
        // 建立连接
        public void SocketConnect()
        {
            IPAddress ip = IPAddress.Parse(GameRole.loginInfo.ServerIP);
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, GameRole.loginInfo.ServerTcpPort));
                // 异步等待接收数据
                thread = new Thread(delegate()
                     {
                         while (true)
                         {
                             if (clientSocket != null)
                             {
                                 int receiveLength = clientSocket.Receive(GameRole.dataBytes);

                                 if (receiveLength > 0)
                                 {
                                     Receive(receiveLength, GameRole.dataBytes);
                                 }
                                 else
                                 {
                                     clientSocket.Shutdown(SocketShutdown.Both);
                                     clientSocket.Close();
                                     clientSocket = null;
                                     PutMessage(string.Format("Sid:{0} Rid:{1},连接中断！", GameRole.loginInfo.Sid, GameRole.loginInfo.Uid));
                                     break;
                                 }
                             }
                         }
                     });
                thread.Start();
            }
            catch (Exception ex)
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
                clientSocket = null;
                PutMessage(ex.Message);
                System.Windows.Forms.MessageBox.Show(clientSocket == null ? "true" : "false");
                return;
            }
        }
        // 发送数据
        public void TcpPost(byte[] buffer)
        {
            try
            {
                clientSocket.Send(buffer);
            }
            catch (Exception ex)
            {
                if (clientSocket != null)
                {
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    clientSocket = null;
                }
                PutMessage(string.Format("请求失败！Rid:{0},{1}", GameRole.loginInfo.Rid, ex.Message));
            }
        }

        public void StopConnect()
        {
            thread.Abort();
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
            clientSocket = null;
            GameRole.Clear();
        }
        #endregion

        #region 日志输出
        public static Queue<string> MessageList = new Queue<string>();
        public void PutMessage(string msg)
        {
            MessageList.Enqueue(string.Format("[{0}]{1}", DateTime.Now.ToString("HH:mm:ss"), msg));
        }
        #endregion

        #region 连接检测
        /// <summary>
        /// 连接检测
        /// </summary>
        private static void CheckConnect()
        {
            new Task(() =>
            {
                try
                {

                }
                catch
                {

                }
            }).Start();
        }
        #endregion

        // 接收数据
        public static Dictionary<int, CallbackAction> callCache = new Dictionary<int, CallbackAction>();
        public void Receive(int leng, byte[] data)
        {
            Bytebuffer buffer = new Bytebuffer(false);
            data.CopyTo(buffer.Data, 0);
            buffer.ReadHead();

            if (callCache.ContainsKey(buffer.ActionId))
            {
                callCache[buffer.ActionId].DoAction(buffer);
            }
            else
            {
                PutMessage(string.Format("Rid:{0}, 未处理的接口:{1}, 字节数:{2}", GameRole.loginInfo.Rid, buffer.ActionId, leng));
            }
        }

    }
    public class CallbackAction
    {
        public Bytebuffer Buffer { get; set; }
        public Action Action { get; set; }

        public CallbackAction()
        {
        }
        public void SetAction(Action action)
        {
            this.Action = action;
        }
        public void DoAction(Bytebuffer buffer)
        {
            Buffer = buffer;
            Action();
        }
    }
}
